package org.as4game.common.loader
{
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.IOErrorEvent;
	import flash.events.ProgressEvent;
	import flash.events.SecurityErrorEvent;
	import flash.net.URLLoader;
	import flash.net.URLLoaderDataFormat;
	import flash.net.URLRequest;
	import flash.utils.ByteArray;
	import org.as4game.resource.base.Resource;
	
	/**
	 * 用于加载资源
	 */
	public class DataLoader extends EventDispatcher
	{
		static public const EVT_COMPLETE:String = "EVT_COMPLETE";		// 加载完成, 用 is_loaded 判断是否成功
		
		// 加载之前
		public var mUrl:String;
		public var mResource:Resource;
		public var mData:Object;
		
		// 加载中
		public var mLoader:URLLoader;
		public var mBytesLoaded:uint;
		public var mBytesTotal:uint;
		
		// 加载完成
		public var mStream:ByteArray;
		
		
		//
		public function DataLoader(url:String, resource:Resource, data:Object)
		{
			mUrl = url;
			mResource = resource;
			mData = data;
		}
		
		/**
		 * 判断是否加载成功
		 */
		public function get is_loaded():Boolean{
			return mStream != null;
		}
		
		/**
		 * 开始读入资源
		 */
		public function load():void{
			if( mLoader || mStream ){
				throw new Error("重复加载");
			}
			
			mLoader = new URLLoader;
			mLoader.dataFormat = URLLoaderDataFormat.BINARY;
			mLoader.addEventListener( Event.COMPLETE, onComplete);
			mLoader.addEventListener( SecurityErrorEvent.SECURITY_ERROR, onError);
			mLoader.addEventListener( IOErrorEvent.IO_ERROR, onError);
			mLoader.addEventListener( ProgressEvent.PROGRESS, onProgress);
			mLoader.load( new URLRequest(mUrl) );
		}
		
		private function onComplete(event:Event):void{
			mStream = mLoader.data as ByteArray;
			this.dispatchEvent( new Event( EVT_COMPLETE ) );
			mLoader = null;
		}
		private function onError(event:Event):void{
			mLoader = null;
			mStream = null;
			this.dispatchEvent( new Event( EVT_COMPLETE ) );
		}
		private function onProgress( event:ProgressEvent ):void{
			mBytesLoaded = event.bytesLoaded;
			mBytesTotal = event.bytesTotal;
		}
	}
}